<?php

namespace App\Repositories\Admin;


use App\Exceptions\ConditionException;
use App\Repositories\BaseRepository;
use App\Services\RoleService;

class RoleRepository extends BaseRepository
{
    /**
     * @var RoleService
     */
    private $service;


    /**
     * RoleService constructor.
     * @param RoleService $service
     */
    public function __construct(RoleService $service)
    {
        $this->service = $service;
    }

    /**
     * 创建
     * @param array $data
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function doCreate(array $data)
    {
        $this->service->beginTransaction();
        try {
            $info = $this->service->create($data);

            if (isset($data['permission_id']) ) {
                $info->permissions()->sync($data['permission_id']);
            }

            if (isset($data['menus_id']) ) {
                $info->menus()->sync($data['menus_id']);
            }

            $this->service->commit();
            return $info;
        }catch (\Exception $e) {
            $this->service->rollBack();
            throw new ConditionException($e->getMessage());
        }
    }

    /**
     * 修改
     * @param array $data
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function doUpdate(array $data, $id)
    {
        $this->service->beginTransaction();
        try {
            $info = $this->service->find($id);
            $info->fill($data)->save();

            if (isset($data['permission_id']) ) {
                $info->permissions()->sync($data['permission_id']);
            }

            if (isset($data['menus_id']) ) {
                $info->menus()->sync($data['menus_id']);
            }

            $this->service->commit();
            return $info;
        }catch (\Exception $e) {
            $this->service->rollBack();
            throw new ConditionException($e->getMessage());
        }
    }

}
